package com.patzn.osgi.tracker.http.core;

import com.patzn.osgi.tracker.http.api.RequestHandler;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.ServiceTracker;

public class HttpCoreActivator implements BundleActivator {

    private HttpServer httpServer;
    private ServiceTracker<RequestHandler, RequestHandler> serviceTracker;

    @Override
    public void start(BundleContext bundleContext) throws Exception {
        // 启动 http server
        httpServer = new HttpServer();
        new Thread(() -> {
            try {
                httpServer.start();

                System.out.println("http server start");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

        serviceTracker = new ServiceTracker<>(
                bundleContext, RequestHandler.class.getName(), new HttpCoreTrackerCustomizer(httpServer, bundleContext)
        );
        serviceTracker.open();
    }

    @Override
    public void stop(BundleContext bundleContext) throws Exception {
        httpServer.stop();
        serviceTracker.close();
    }
}
